package com.cmw.auntapp.ui;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.cmw.auntapp.R;
import com.cmw.auntapp.component.SendCountDownTimer;
import com.cmw.auntapp.constant.CommandType;
import com.cmw.auntapp.constant.Constant;
import com.cmw.auntapp.core.base.vo.DataResult;
import com.cmw.auntapp.core.util.SharedPreferencesUtil;
import com.cmw.auntapp.model.UserModel;
import com.cmw.auntapp.presenter.LoginPresenter;
import com.cmw.auntapp.presenter.MsgPresenter;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;

import static com.cmw.auntapp.constant.Constant.ATTACHMENT_FORMTYPE_50;
import static com.cmw.auntapp.constant.Constant.IS_GOTO_LOGIN_KEY;

/**
 * 登录页面
 * @Auth chengmingwei
 * @date 2021-04-05 16:48
 */
public class LoginActivity  extends BaseActivity {

    @BindView(R.id.ed_phone)
    EditText edPhone;

    // ed_sms_code
    @BindView(R.id.ed_sms_code)
    EditText edSmsCode;


    //btn_sms_code
    @BindView(R.id.btn_sms_code)
    Button btnSmsCode;

    @BindView(R.id.chk_agreement)
    CheckBox chkAgreement;

    @BindView(R.id.btn_login)
    Button btnLogin;

    LoginPresenter loginPresenter;

    MsgPresenter msgPresenter;

    SendCountDownTimer countDownTimer = null;

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_login;
    }

    @Override
    void onInit(Bundle savedInstanceState) {
        setTitle(R.string.login_title);
        loginPresenter = new LoginPresenter(this);
        msgPresenter = new MsgPresenter(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume...");
        loadData();
    }

    @Override
    protected void onDestroy() {
        Constant.isGoLogin = false;
        super.onDestroy();
    }

    private void loadData() {
        SharedPreferencesUtil.getInstance(this).remove(IS_GOTO_LOGIN_KEY);
    }

    @OnClick(R.id.btn_login)
    public void login(View view) {
        UserModel userModel = new UserModel();
        userModel.setUserName(edPhone.getText().toString());
        userModel.setPassword(edSmsCode.getText().toString());
        Map<String, String> errResult = loginPresenter.valid(userModel);
        if (errResult != null && errResult.size() > 0) {
            if(!TextUtils.isEmpty(errResult.get("userName"))) {
                edPhone.setError(errResult.get("userName"));
                edPhone.requestFocus();
                return;
            }
            if(!TextUtils.isEmpty(errResult.get("passWord"))) {
                edSmsCode.setError(errResult.get("passWord"));
                edSmsCode.requestFocus();
                return;
            }
        } else {
            if (!chkAgreement.isChecked()) {
                chkAgreement.setError("请勾选并同意《用户协议》");
                chkAgreement.requestFocus();
                return;
            }
            loginPresenter.login(userModel);
        }
    }

    @OnTextChanged(R.id.ed_sms_code)
    public void smsCodeTextChange(CharSequence text) {
        int length = text.length();
        Log.i(TAG, text.toString()+", length = "+length);
        Drawable btnBackground = getResources().getDrawable(R.drawable.btn_big_nomal);
        if (length == 6) {
            btnBackground = getResources().getDrawable(R.drawable.btn_big_active);
        }
        btnLogin.setBackground(btnBackground);
    }

    /**
     * 发送短信验证码
     * @param view
     */
    @OnClick(R.id.btn_sms_code)
    public void sendSmsCode(View view){
        //android 短信验证码倒计时60秒 参考：
        //https://blog.csdn.net/qq_24735175/article/details/80095709
        String errMsg = loginPresenter.validPhone(edPhone.getText().toString());
        if (!TextUtils.isEmpty(errMsg)) {
            edPhone.setError(errMsg);
            edPhone.requestFocus();
            return;
        } else {
            Button btnSmsCode = (Button)view;
            String phone = edPhone.getText().toString();
            msgPresenter.sendSmsCode(phone);

        }
    }


    /**
     * 查看用户协议
     * @param view
     */
    @OnClick(R.id.tv_user_agreement)
    public void viewAgreement(View view){
        Map<String, String> params = new HashMap<>();
        params.put("formType", ATTACHMENT_FORMTYPE_50+"");
        go(HtmlContentActivity.class, params);
    }

    @Override
    public boolean doSuccess(CommandType commandType, DataResult dataResult) {
        switch (commandType) {
            case USER_LOGIN:{ //跳转到指定页面
                Constant.isGoLogin = false;
                gotoBack(MainActivity.class);
                break;
            }case GET:{ // 短信发送成功倒计时
                Drawable nomalBackground = getResources().getDrawable(R.drawable.btn_sms_code_nomal);
                Drawable activeBackground = getResources().getDrawable(R.drawable.btn_sms_code_active);
                countDownTimer = new SendCountDownTimer(btnSmsCode,nomalBackground, activeBackground,
                        60000, 1000);
                countDownTimer.start();
            }
        }
        return true;
    }

    @Override
    public boolean doFailure(CommandType commandType, DataResult dataResult) {
        switch (commandType) {
            case USER_LOGIN:{ //登录失败
                Toast.makeText(this, dataResult.getMsg(), Toast.LENGTH_SHORT).show();
                break;
            }case GET:{ // 短信发送失败
                String errMsg = dataResult.getMsg();
                if (TextUtils.isEmpty(errMsg)) errMsg = getResources().getResourceName(R.string.err_tip_send_sms_failure);
                Toast.makeText(this, errMsg, Toast.LENGTH_SHORT).show();
                if (null != countDownTimer) countDownTimer.cancel();
                btnSmsCode.setText(getResources().getText(R.string.login_btn_send_code));
                btnSmsCode.setBackground(getResources().getDrawable(R.drawable.btn_sms_code_active));
                //设置可点击
                btnSmsCode.setClickable(true);
                break;
            }
        }
        return true;
    }
}
